import React from  'react';
import { observer, inject } from 'mobx-react';
import { Button,Modal,Table,Col,Row,Icon,message } from 'antd';
import { WeaDialog,WeaTableEdit,WeaTools,WeaPopoverHrm,WeaRightMenu, WeaLocaleProvider } from 'ecCom';
import './style/share.css';
const getLabel = WeaLocaleProvider.getLabel;
import WfAddShareStore from '../../stores/share/wfAddShareStore';
import WfAddShare from './AddShare';

const wfAddShareStore = new WfAddShareStore();
@observer
export default class Main extends React.Component{
    constructor(props){
        super(props);
    }

    toogleAddShare(){
        wfAddShareStore.setState({visible:true})
    }

    doDelete(){

        const { wfShareBatchStore } = this.props;
        let {selectedRowKeys,datas} = wfShareBatchStore;
        let newArr = datas.slice();
        let selectedKeys = selectedRowKeys.slice().sort();
        let newDatas = [];

        newDatas = newArr.filter((item,index)=> {
            if(selectedKeys.indexOf(index) < 0){
                return true;
            }
        })

        Modal.confirm({
            title: getLabel(131329,'信息确认'),
            content: getLabel(15097,'确定要删除吗？'),
            okText: getLabel(83446,'确定'),
            cancelText: getLabel(31129,'取消'),
            onOk: ()=>{
                wfShareBatchStore.setSelectedRowKeys([]);
                wfShareBatchStore.setDatas([...newDatas]);
            }
        });

    }

    addHandleOk (v = {},allObjInfo = [],jobObjInfo = []) {

        const { wfShareBatchStore } = this.props;
        const {datas,setDatas} = wfShareBatchStore;

        let newDates = datas.slice();
        let dataObj = {};

        let {permissiontype,iscanread,objValue,seclevel,seclevelMax,rolelevel,joblevel,relatedshareid_6} = v;

        if(allObjInfo.length === 0){
            allObjInfo.push(
                {
                    link : ''
                }
            )
        }


        switch (Number(permissiontype)){
            case 5 :   //人力资源
                allObjInfo.forEach((item,index)=>{
                    dataObj.permissiontype = permissiontype;
                    dataObj.obj = {link:item.id,name:item.name,id:item.id};
                    dataObj.userid = item.id;
                    dataObj.iscanread = iscanread;
                    newDates.push(dataObj);
                    dataObj = {};
                })
                break;
            case 6 :    //分部
            case 1 :   //部门
                allObjInfo.forEach((item,index)=>{
                    dataObj.permissiontype = permissiontype;
                    dataObj.obj = {link:item.link,name:item.name,id:item.id};
                    dataObj.seclevel = seclevel;
                    dataObj.seclevelMax = seclevelMax;
                    dataObj.iscanread = iscanread;
                    if(Number(permissiontype) === 1){
                        dataObj.departmentid = item.id;
                    }
                    if(Number(permissiontype) === 6){
                        dataObj.subids = item.id;
                    }
                    newDates.push(dataObj);
                    dataObj = {};
                })
                break;
            case 3 :   //所有人
                allObjInfo.forEach((item,index)=>{
                    dataObj.permissiontype = permissiontype;
                    dataObj.obj = {link:'',name:'',id:''};
                    dataObj.seclevel = seclevel;
                    dataObj.seclevelMax = seclevelMax;
                    dataObj.iscanread = iscanread;
                    newDates.push(dataObj);
                    dataObj = {};
                })
                break;
            case 2 :   //角色
                allObjInfo.forEach((item,index)=>{
                    dataObj.permissiontype = permissiontype;
                    dataObj.obj = {link:item.link,name:item.name,id:item.id};
                    dataObj.seclevel = seclevel;
                    dataObj.seclevelMax = seclevelMax;
                    dataObj.rolelevel = rolelevel;
                    dataObj.iscanread = iscanread;
                    dataObj.roleid = item.id;
                    newDates.push(dataObj);
                    dataObj = {};
                })
                break;
            case 7 :   //岗位
                allObjInfo.forEach((item,index)=>{
                    dataObj.permissiontype = permissiontype;
                    dataObj.obj = {link:item.link,name:item.name,id:item.id};
                    dataObj.joblevel = joblevel;
                    dataObj.relatedshareid_6 = relatedshareid_6;
                    dataObj.jobid = item.id;
                    dataObj.iscanread = iscanread;
                    dataObj.jobObjInfo = jobObjInfo;
                    newDates.push(dataObj);
                    dataObj = {};
                })
                break;
            default :
                break ;
        }

        setDatas([...newDates]);
        this.addHandleCancel();

    }

    addHandleCancel () {
        const { wfShareBatchStore } = this.props;
        wfShareBatchStore.toogleAddShare(false);
    }

    handleOk(){
        let { wfShareBatchStore } = this.props;
        let { ids } = this.props;
        const {datas,addShare} = wfShareBatchStore;

        let rowNumber = datas.length;

        if(rowNumber === 0){
            message.warning(getLabel(385086,'请先添加共享'));
            return ;
        }

        let idsNew = "";
        ids && ids.map(v => {
            const requestid = v.split("_")[0];
            idsNew += ","+requestid;
        });
        if(idsNew !== "")
            idsNew = idsNew.substring(1);

        let params = {};

        datas.forEach((item,index)=>{
            let keys = Object.keys(item);
            for(let i = 0;i < keys.length;i++){
                let key = keys[i];

                if(key === 'obj' || key === 'jobObjInfo'){
                    continue ;
                }else{
                    params[key+'_'+index] = item[key];
                }
            }
        })

        addShare({rowNumber,ids:idsNew,...params});
        this.handleCancel()
    }

    handleCancel(){
        const { wfShareBatchStore } = this.props;
        wfShareBatchStore.setDatas([]);
        this.props.controlModal(false);
    }

    getRowSelection() {
        const { wfShareBatchStore } = this.props;
        const { selectedRowKeys } = wfShareBatchStore;
        return {
            selectedRowKeys,
            onChange : (sRowKeys) => {
                wfShareBatchStore.setSelectedRowKeys([...sRowKeys]);
            },
        }
    }

    getTitle(){
        const { wfShareBatchStore } = this.props;
        const {selectedRowKeys} = wfShareBatchStore;
        return (
            <Row ecId={`${this && this.props && this.props.ecId || ''}_Row@hk7ydp`} className="wea-table-edit-title" >
                <Col ecId={`${this && this.props && this.props.ecId || ''}_Col@widqe2`}>
                    { getLabel(383655,'添加共享') }

                    <Button ecId={`${this && this.props && this.props.ecId || ''}_Button@rs0iey`} style={{border:'none',padding:'0px',fontSize:'20px',lineHeight:'1',color: selectedRowKeys.length <= 0 ? '#d8d8d8':'#55a1f8',marginLeft:'10px',backgroundColor: '#fff'}} type="primary" title={getLabel(126371,'删除')} size="small" disabled={selectedRowKeys.length <= 0} onClick={()=>this.doDelete()}><span className="icon-coms-form-delete-hot"/></Button>
                    <Button ecId={`${this && this.props && this.props.ecId || ''}_Button@conxtg`} style={{border:'none',padding:'0px',fontSize:'20px',lineHeight:'1',color:'#55a1f8',backgroundColor:'#fff'}} type="primary" title={getLabel(611,'添加')} size="small" onClick={()=>this.toogleAddShare()}><span className="icon-coms-Add-to-hot"/></Button>

                </Col>
            </Row>
        )
    }

    getHrmCard (text,record){

        let other = '';

        const link = text.link;
        const name = text.name;

        if(record && record.permissiontype === 2){
            switch (record.rolelevel){
                case '0' : other = `/${getLabel(124,"部门")}`; break;
                case '1' : other = `/${getLabel(141,"分部")}`; break;
                default : other = `/${getLabel(140,"总部")}`; break;
            }
            return (
                <div title={name + other}>{name}{other}</div>
            )
        }

        if(record && record.permissiontype === 7){
            switch (Number(record.joblevel)){
                case 2 :
                    other = `/${getLabel(140,"总部")}`;
                    return (
                        <div title={name + other}>{name}{other}</div>
                    );
                case 1 :
                    other = `/${getLabel(19437,"指定分部")}`;
                    let title = name + other + '(';
                    let content = record.jobObjInfo.map((item, index) => {
                        title += item.name;
                        if (index === record.jobObjInfo.length - 1) {
                            return <a className="objA" title={item.name} href={`${item.link}`} target="_blank">{item.name}</a>;
                        } else {
                            title += ',';
                            return (
                                <span>
                                    <a className="objA" title={item.name} href={`${item.link}`} target="_blank">{item.name}</a>,
                                </span>
                            )
                        }

                    });
                    title += ')';
                    return (
                        <div title={title} style={{display:'inline-block'}}>
                            {name + other + '('}
                            {
                                content
                            }
                            {')'}
                        </div>
                    )
                default :
                    other = `/${getLabel(19438,"指定部门")}`;
                    let titleDepartment = name + other + '(';
                    let contentDepartment = record.jobObjInfo.map((item, index) => {
                        titleDepartment += item.name;
                        if (index === record.jobObjInfo.length - 1) {
                            return <a className="objA" title={item.name} href={`${item.link}`} target="_blank">{item.name}</a>;
                        } else {
                            titleDepartment += ',';
                            return (
                                <span>
                                    <a className="objA" title={item.name} href={`${item.link}`} target="_blank">{item.name}</a>,
                                </span>
                            )
                        }

                    });
                    titleDepartment += ')';
                    return (
                        <div title={titleDepartment} style={{display:'inline-block'}}>
                            {name + other + '('}
                            {
                                contentDepartment
                            }
                            {')'}
                        </div>
                    )
            }
        }

        if(link.indexOf('/') > -1){
            return (
                <a title={name + other} className="objA" href={`${link}`} target="_blank">
                    {name}
                    {other}
                </a>
            )
        }else {
            return (
                //人力资源
                <a title={name} className="wea-hrm-card objA" href={`javaScript:openhrm(${link})`} onClick={event => window.pointerXY(event)}>{name}</a>
            )
        }

    }

    getMoreBtns () {
        let btns = {
            datas: [],
            collectParams: {
                favname: getLabel(2112,'共享设置'),
                favouritetype: 2,
                objid: 0,
                importantlevel: 1,
            }
        };
        btns.datas.push(
            {
                key: '1',
                disabled: false,
                icon: <i className='icon-coms-Batch-sharing'/>,
                content: getLabel(119,'共享'),
                onClick: key => this.handleOk(),
            }
        )

        return btns;

    }

    render () {
        const footer = [
            <Button ecId={`${this && this.props && this.props.ecId || ''}_Button@pykdwq@share`} key="save" type="primary" onClick={() => this.handleOk()}>{getLabel(119,'共享')}</Button>,
        ];
        const { wfShareBatchStore } = this.props;
        const { visible } = this.props;
        let { datas } = wfShareBatchStore;
        datas = datas.slice();
        const columns = [
            {
                title: getLabel(21956,"对象类型"), //列名
                dataIndex: 'permissiontype', //列的id 对应数据
                key: 'permissiontype', //前端渲染key值
                render : (text) => {
                    let permission;
                    switch (Number(text)){
                        case 1 :
                            permission = getLabel(124,"部门");
                            break;
                        case 6 :
                            permission = getLabel(141,"分部");
                            break;
                        case 3 :
                            permission = getLabel(1340,"所有人");
                            break;
                        case 2 :
                            permission = getLabel(122,"角色");
                            break;
                        case 5 :
                            permission = getLabel(383424,"人力资源");
                            break;
                        case 7 :
                            permission = getLabel(6086,"岗位");
                            break;
                        default :
                            console.log('没有相应类型');
                    }
                    return (
                        <span>{permission}</span>
                    )
                },
                colSpan: 1,
                width: '20%',
                className: 'wea-table-edit-permissiontype',
            },
            {
                title: getLabel(106,'对象'), //列名
                dataIndex: 'obj', //列的id 对应数据
                key: 'obj', //前端渲染key值
                render : (text, record) => {
                    if(text.name === ""){
                        return <div style={{minHeight : '16px'}}> </div> ;
                    }else {
                        return (
                            this.getHrmCard(text,record)
                        )
                    }
                },
                colSpan: 1,
                width: '215px',
                className: 'wea-table-edit-obj',
            },
            {
                title: getLabel(683,"安全级别"),
                dataIndex: 'safeLevel',
                key: 'safeLevel',
                render: (text, record) => {
                    // console.log('record', record);
                    if (Number(record.permissiontype) === 5 || Number(record.permissiontype) === 7) {
                        return ;
                    } else {
                        return (
                            <span>{record.seclevel}-{record.seclevelMax}</span>
                        )
                    }

                },
                colSpan: 1,
                width: '20%',
                className: 'wea-table-edit-safeLevel',
            },
            {
                title: getLabel(125734,"流转意见"),
                dataIndex: 'iscanread',
                key: 'iscanread',
                render : (text,record) => {
                    return (
                        <span>{Number(text) === 1 ? getLabel(20306,"可查看") : getLabel(82613,"不可查看")}</span>
                    )
                },
                colSpan: 1,
                width: '20%',
                className: 'wea-table-edit-iscanread',
            },
            {
                title: getLabel(82615,'共享添加人'),
                dataIndex: 'adder',
                key: 'adder',
                render : (text,record) => {
                    const username = WeaTools.ls.getJSONObj('theme-account').username;
                    const userid = WeaTools.ls.getJSONObj('theme-account').userid;
                    return (
                        this.getHrmCard({link:userid,name:username})
                    )
                },
                colSpan: 1,
                width: '15%',
                className: 'wea-table-edit-adder',
            },
        ];

        return (
            <div>
                <WeaDialog ecId={`${this && this.props && this.props.ecId || ''}_WeaDialog@ayi72h`}
                    className="wf-shareBatch"
                    title={getLabel(2112,'共享设置')}
                    visible={visible}
                    icon="icon-coms-workflow"
                    iconBgcolor='#0079DE'
                    maskClosable={false}
                    buttons={footer}
                    onCancel={() => this.handleCancel()}
                    style={{width:'1000px',height:'410px'}}
                    moreBtn={this.getMoreBtns()}
                >

                    <WeaRightMenu ecId={`${this && this.props && this.props.ecId || ''}_WeaRightMenu@mllipz`}
                        {...this.getMoreBtns()}
                    >

                        <WfAddShare ecId={`${this && this.props && this.props.ecId || ''}_WfAddShare@jn52p6`}
                            wfAddShareStore={wfAddShareStore}
                            onOk={(v,allObj,jobObj)=>this.addHandleOk(v,allObj,jobObj)}
                        />

                        <div className="wea-table-edit">
                            {this.getTitle()}
                            <Table ecId={`${this && this.props && this.props.ecId || ''}_Table@3hwuou`}
                                columns={columns}
                                dataSource={datas}
                                pagination={false}
                                rowSelection={this.getRowSelection()}
                                scroll={{ y: 200 }}
                            />
                        </div>
                    </WeaRightMenu>
                </WeaDialog>
            </div>
        )
    }
}